﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AnguaRPGEngine.Library.Packages;

namespace AnguaRPGEngine.Library.Systems
{
    public class PackageBuffer
    {
        private List<BufferPackage> _TempBuffer;
        private Queue<BufferPackage> _Buffer;
        private System.Timers.Timer _TempBufferTimer;
        public PackageBuffer()
        {
            _TempBuffer = new List<BufferPackage>();
            _TempBufferTimer = new System.Timers.Timer(1000);
            _TempBufferTimer.Elapsed += new System.Timers.ElapsedEventHandler(_TempBufferTimer_Elapsed);
            _Buffer = new Queue<BufferPackage>();
            _TempBufferTimer.Start();
        }

        void _TempBufferTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {

            if (_TempBuffer.Count > 0)
            {
                lock (_TempBuffer)
                {
                    BufferPackage bp = _TempBuffer[0];
                    if (Tools.IsCompletePackage(bp.Package))
                    {
                        AddMessage(bp.ClientSocketGuid, bp.Package);
                    }
                    else
                    {
                        int pos = bp.Package.IndexOf(Constants.EndOfPacket);
                        AddMessage(bp.ClientSocketGuid, bp.Package.Substring(0, pos + Constants.EndOfPacket.Length));
                        bp.Package = bp.Package.Remove(0, pos + Constants.EndOfPacket.Length);
                    }
                }
            }
        }
        public void AddMessage(Guid clientSocketGuid,string package)
        {
            if (Tools.IsCompletePackage(package))
            {
                _Buffer.Enqueue(new BufferPackage(clientSocketGuid, Tools.GetMessageFromPackage( package)));
            }
            else
            {
                lock (_TempBuffer)
                {
                    try
                    {
                        BufferPackage bp = _TempBuffer.Last(p => p.ClientSocketGuid == clientSocketGuid);
                        if (bp != null)
                        {
                            bp.Package += package;
                        }
                    }
                    catch
                    {
                        _TempBuffer.Add(new BufferPackage(clientSocketGuid, package));
                    }
                }
            }
        }
        public BufferPackage GetMessage()
        {
            if (_Buffer.Count > 0)
            {
                return _Buffer.Dequeue();
            }
            return null;

        }
        public bool HasMessage
        {
            get
            {
                return _Buffer.Count > 0;
            }
        }
    }
}
